<template>
  <div class="login-container">
    <!-- 左侧蓝色背景区域 -->
    <div class="left-section">
      <Canvas-wave />
      <chicken-soup class="chickenSoup" />
    </div>

    <!-- 右侧白色背景区域 -->
    <div class="right-section">
      <div class="right-content">
        <h2>WELCOME BACK</h2>
        <p class="login-prompt">请登录您的账户</p>

        <form @submit.prevent="handleLogin" class="login-form">
          <div class="form-group">
            <label for="username">用户名</label>
            <div class="input-wrapper">
              <i class="iconfont icon-user input-icon"></i>
              <input
                type="text"
                id="username"
                v-model="loginForm.username"
                @blur="validateUsername"
                @input="clearError('username')"
                placeholder="请输入您的用户名"
                :class="{ 'input-error': errors.username }"
              />
              <transition name="fade">
                <div v-if="errors.username" class="error-tooltip">
                  <i class="iconfont icon-error"></i>
                  <span>{{ errors.username }}</span>
                </div>
              </transition>
            </div>
          </div>

          <div class="form-group">
            <label for="password">密码</label>
            <div class="input-wrapper">
              <i class="iconfont icon-lock input-icon"></i>
              <input
                type="password"
                id="password"
                v-model="loginForm.password"
                @blur="validatePassword"
                @input="clearError('password')"
                placeholder="请输入您的密码"
                :class="{ 'input-error': errors.password }"
              />
              <transition name="fade">
                <div v-if="errors.password" class="error-tooltip">
                  <i class="iconfont icon-error"></i>
                  <span>{{ errors.password }}</span>
                </div>
              </transition>
            </div>
          </div>

          <div class="forgot-password">
            <a href="#"><i class="iconfont icon-help"></i> 忘记密码</a>
          </div>

          <button
            type="submit"
            class="login-button"
            :disabled="!formValid || loading"
          >
            <template v-if="loading">
              <i class="iconfont icon-loading"></i> 登录中...
            </template>
            <template v-else> 登录 </template>
          </button>
        </form>

        <!-- <div class="social-login">
          <p>或使用以下方式登录</p>
          <div class="social-icons">
            <button class="social-button facebook">
              <i class="iconfont icon-wechat"></i>
              <span>微信</span>
            </button>
            <button class="social-button google">
              <i class="iconfont icon-google"></i>
              <span>Google</span>
            </button>
          </div>
        </div> -->
      </div>
    </div>
  </div>
</template>
    
<script setup>
import { ref, computed, onMounted } from "vue";
import { useRouter } from "vue-router";
import ChickenSoup from "@/components/chickenSoup.vue";
import CanvasWave from "@/components/canvas/wave.vue";
import { post } from "@/utils/request";
import { vToast } from "@/plugins/vToast";
import { saveToken, saveUserInfo, fetchUserInfo } from "@/utils/auth";

// 组件挂载时清空localStorage
onMounted(() => {
  localStorage.clear();
});

const router = useRouter();
const loading = ref(false);
const loginForm = ref({
  username: "",
  password: "",
});

const errors = ref({
  username: "",
  password: "",
});

// 计算属性，检查表单是否有效
const formValid = computed(() => {
  return (
    loginForm.value.username.trim().length >= 3 &&
    loginForm.value.password.trim().length >= 6 &&
    !errors.value.username &&
    !errors.value.password
  );
});

// 用户名验证
const validateUsername = () => {
  const username = loginForm.value.username.trim();
  if (!username) {
    errors.value.username = "请输入用户名";
    return false;
  }
  if (username.length < 3) {
    errors.value.username = "用户名长度不能少于3位";
    return false;
  }
  errors.value.username = "";
  return true;
};

// 密码验证
const validatePassword = () => {
  const password = loginForm.value.password.trim();
  if (!password) {
    errors.value.password = "请输入密码";
    return false;
  }
  if (password.length < 6) {
    errors.value.password = "密码长度不能少于6位";
    return false;
  }
  errors.value.password = "";
  return true;
};

// 清除错误信息
const clearError = (field) => {
  if (loginForm.value[field].trim()) {
    errors.value[field] = "";
  }
};

// 表单提交
const handleLogin = async () => {
  const isUsernameValid = validateUsername();
  const isPasswordValid = validatePassword();

  if (isUsernameValid && isPasswordValid) {
    try {
      loading.value = true;
      const res = await post(`/admin/login`, {
        username: loginForm.value.username,
        password: loginForm.value.password,
      });
      if (res && res.code === 200) {
        // 检查是否为超级管理员权限
        if (res.data.permission !== 'superadmin' && res.data.permission !== 'assistant') {
          vToast.error("您不是超级管理员 无法登录");
          return;
        }

        // 保存token到localStorage
        const token = res.data.token;
        const expire = res.data.token_expire;
        saveToken(token, expire);

        // 保存用户信息到localStorage
        if (res.data.user_info) {
          saveUserInfo(res.data.user_info);
        } else {
          // 如果登录返回中没有用户信息，主动获取
          try {
            await fetchUserInfo();
          } catch (error) {
            console.warn("尝试获取用户信息失败，但不影响登录流程:", error);
          }
        }

        vToast.success(`登录成功，跳转中...`);
        // 跳转到首页或重定向页面
        const redirectPath = router.currentRoute.value.query.redirect || "/";
        setTimeout(() => {
          router.replace(redirectPath);
        }, 500);
      } else {
        // 处理其他状态码
        vToast.error(`登录失败: ${res.msg}`);
      }
    } catch (err) {
      vToast.error("登录请求错误:", err);
    } finally {
      loading.value = false;
    }
  }
};
</script>
  <style lang="less" scoped>
/* 引入图标字体 */
.login-container {
  display: flex;
  height: 100vh;

  /* 左侧区域样式 */
  .left-section {
    flex-grow: 1;
    background-color: var(--v-sidebar-background);
    color: white;
    display: flex;
    justify-content: center;
    align-items: center;
    padding: 2rem;
    position: relative;
    overflow: hidden;

    .left-content {
      max-width: 400px;
      position: relative;
      z-index: 2;
      text-align: center;

      h1 {
        font-size: 2.2rem;
        font-weight: 200;
        line-height: 1.6;
        margin-bottom: 1.5rem;
      }

      p {
        font-size: 1rem;
        line-height: 1.8;
        margin-bottom: 2rem;
        color: rgba(255, 255, 255, 0.9);
      }
    }
  }

  /* 右侧区域样式 */
  .right-section {
    max-width: 600px;
    flex-grow: 1;
    background-color: var(--v-background-pure);
    display: flex;
    justify-content: center;
    align-items: center;

    .right-content {
      max-width: 380px;
      width: 100%;
      padding: 0 1.5rem;

      .logo {
        font-size: 1.5rem;
        font-weight: 600;
        margin-bottom: 1rem;
        color: var(--v-warning);
        display: flex;
        align-items: center;
        justify-content: center;

        .iconfont {
          font-size: 4rem;
        }
      }

      h2 {
        font-size: 1.6rem;
        font-weight: 600;
        margin-bottom: 0.8rem;
        color: var(--v-text-darker);
        display: flex;
        align-items: center;
        justify-content: center;
      }

      .login-prompt {
        color: var(--v-text-lighter);
        margin-bottom: 2rem;
        text-align: center;
        font-size: 0.95rem;
      }

      .form-group {
        margin-bottom: 1.5rem;
        position: relative;

        label {
          display: block;
          margin-bottom: 0.5rem;
          font-weight: 500;
          color: var(--v-text-darker);
          font-size: 0.95rem;
        }

        .input-wrapper {
          position: relative;

          .input-icon {
            position: absolute;
            left: 12px;
            top: 50%;
            transform: translateY(-50%);
            color: var(--v-text-lighter);
            z-index: 2;
          }

          input {
            width: 100%;
            padding: 0.8rem 0.8rem 0.8rem 2.5rem;
            border: 1px solid var(--v-border-color);
            border-radius: var(--v-card-radius);
            font-size: 0.95rem;
            background-color: var(--v-background-pure);
            transition: all 0.3s;

            &:focus {
              outline: none;
              border-color: var(--v-theme);
              box-shadow: 0 0 0 2px rgba(10, 179, 156, 0.2);
            }

            &.input-error {
              border-color: var(--v-danger);
            }
          }

          .error-tooltip {
            position: absolute;
            top: 100%;
            left: 0;
            margin-top: 0.3rem;
            padding: 0.5rem 0.7rem;
            background-color: var(--v-danger);
            color: white;
            border-radius: var(--v-card-radius);
            font-size: 0.8rem;
            z-index: 10;
            white-space: nowrap;
            box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
            display: flex;
            align-items: center;

            &::before {
              content: "";
              position: absolute;
              bottom: 100%;
              left: 15px;
              border-width: 5px;
              border-style: solid;
              border-color: transparent transparent var(--v-danger) transparent;
            }

            .iconfont {
              margin-right: 0.3rem;
              font-size: 0.9rem;
            }
          }
        }
      }

      /* 错误提示动画 */
      .fade-enter-active,
      .fade-leave-active {
        transition: all 0.2s ease;
      }

      .fade-enter-from,
      .fade-leave-to {
        opacity: 0;
        transform: translateY(-5px);
      }

      .forgot-password {
        text-align: right;
        margin-bottom: 1.5rem;

        a {
          color: var(--v-theme);
          text-decoration: none;
          font-size: 0.9rem;
          display: inline-flex;
          align-items: center;
          transition: color 0.3s;

          &:hover {
            color: var(--v-success);
          }
        }
      }

      .login-button {
        width: 100%;
        padding: 0.9rem;
        background-color: var(--v-theme);
        color: var(--v-background-pure);
        border: none;
        border-radius: var(--v-card-radius);
        font-size: 1rem;
        font-weight: 500;
        cursor: pointer;
        margin-bottom: 2rem;
        transition: all 0.3s;
        display: flex;
        align-items: center;
        justify-content: center;

        &:hover:not(:disabled) {
          background-color: var(--v-success);
        }

        &:disabled {
          background-color: var(--v-text-lighter);
          cursor: not-allowed;
          opacity: 0.7;
        }
      }

      .social-login {
        text-align: center;

        p {
          color: var(--v-text-lighter);
          margin-bottom: 1.2rem;
          position: relative;
          font-size: 0.9rem;

          &::before,
          &::after {
            content: "";
            display: inline-block;
            width: 28%;
            height: 1px;
            background-color: var(--v-border-color);
            position: absolute;
            top: 50%;
          }

          &::before {
            left: 0;
          }

          &::after {
            right: 0;
          }
        }

        .social-icons {
          display: flex;
          justify-content: center;
          gap: 1rem;

          .social-button {
            display: flex;
            align-items: center;
            justify-content: center;
            padding: 0.6rem 1rem;
            border: 1px solid var(--v-border-color);
            border-radius: var(--v-card-radius);
            background-color: var(--v-background-pure);
            cursor: pointer;
            width: 120px;
            transition: all 0.3s;
            font-size: 0.9rem;

            &:hover {
              box-shadow: var(--v-shadow);
            }

            &.facebook {
              color: #07c160; /* 微信绿色 */
            }

            &.google {
              color: #ea4335; /* Google红色 */
            }
          }
        }
      }
    }
  }

  .chickenSoup {
    position: relative;
    z-index: 2;
  }
}

@keyframes rotate {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}

.icon-loading {
  animation: rotate 1s linear infinite;
  margin-right: 8px;
}
</style>